package com.zzz.robot201.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.zzz.robot201.R;
import com.zzz.robot201.app.base.BaseViewActivity;
import com.zzz.robot201.app.config.AppContent;
import com.zzz.robot201.di.component.DaggerMsgFeedbackComponent;
import com.zzz.robot201.mvp.contract.MsgFeedbackContract;
import com.zzz.robot201.mvp.presenter.MsgFeedbackPresenter;
import com.zzz.robot201.mvp.ui.fragment.ConnetFragment;
import com.zzz.robot201.mvp.ui.fragment.ControlFragment;
import com.zzz.robot201.mvp.ui.fragment.DisplayFragment;
import com.zzz.robot201.mvp.ui.fragment.FeedBackFragment;
import com.zzz.robot201.mvp.ui.fragment.MsgFeedBackOneFragment;
import com.zzz.robot201.mvp.ui.fragment.MsgFeedBackTwoFragment;
import com.zzz.robot201.mvp.ui.fragment.RobotFragment;
import com.zzz.robot201.mvp.ui.fragment.SystemFragment;
import com.zzz.robot201.service.api.RobotUdpUtil;
import com.zzz.robot201.service.client.ResponseMsg;
import com.zzz.robot201.service.client.SendMsg;
import com.zzz.robot201.utils.SpUtils;
import com.zzz.robot201.utils.UIUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Date;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import q.rorbin.verticaltablayout.VerticalTabLayout;
import q.rorbin.verticaltablayout.adapter.TabAdapter;
import q.rorbin.verticaltablayout.widget.QTabView;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/10/2020 02:37
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class MsgFeedbackActivity extends BaseViewActivity<MsgFeedbackPresenter> implements MsgFeedbackContract.View {

    @BindView(R.id.btn_back)
    Button btnBack;
    @BindView(R.id.iv_dc)
    ImageView ivDc;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tab_set)
    VerticalTabLayout tabSet;
    @BindView(R.id.fragment_set)
    FrameLayout fragmentSet;
    private ArrayList<String> mTitlesList;
    private ArrayList<Fragment> mFragmentsList;
    public DatagramSocket ds = null;
    private String deviceCode ;
    float up = 0;
    float left = 0;
    byte unsigned_char_byte15_0 = 0;// byte[0] = 当前步态序号
    byte unsigned_char_byte15_4 = 13;// byte[4] = 当前状态序号
    float zx_speed = 0f;//转向速度

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMsgFeedbackComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_msg_feedback; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        setTitle(tvTitle, UIUtils.getString(R.string.title_msg_feedback));
        deviceCode = (String) SpUtils.get(MsgFeedbackActivity.this, AppContent.SaveInfoKey.DEVICECODE, "");
        mTitlesList = new ArrayList<>();//初始化Tab栏数据
        mTitlesList.add("数据显示分区1");
        mTitlesList.add("数据显示分区2");

        mFragmentsList = new ArrayList<>();//添加碎片
        mFragmentsList.add(new MsgFeedBackOneFragment());
        mFragmentsList.add(new MsgFeedBackTwoFragment());

        tabSet.setupWithFragment(getSupportFragmentManager(), R.id.fragment_set, mFragmentsList
                , new TabAdapter() {
                    @Override
                    public int getCount() {
                        return mTitlesList.size();
                    }

                    @Override
                    public QTabView.TabBadge getBadge(int position) {
                        return null;
                    }

                    @Override
                    public QTabView.TabIcon getIcon(int position) {
                        return null;
                    }

                    @Override
                    public QTabView.TabTitle getTitle(int position) {
                        return new QTabView.TabTitle.Builder()
                                .setContent(mTitlesList.get(position))
                                .setTextSize(9)
                                .setTextColor(0xFFFFFFFF,0xFFFFFFFF)
                                .build();
                    }

                    @Override
                    public int getBackground(int position) {
                        return 0;
                    }
                });

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                receiveMsg(deviceCode, 43795);
//            }
//        }).start();

    }
    public static ResponseMsg responseMsg;

    public void receiveMsg(String deviceCode, int localPort) {
        boolean result = false;
        try {
            ds = new DatagramSocket(localPort);
            while (true) {
                byte[] buffer = new byte[260];
                DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
                ds.receive(dp);
                buffer = dp.getData();
                responseMsg = ResponseMsg.getResponseMsg(buffer);

                InetAddress address = dp.getAddress();
                int port = dp.getPort();
                responseMsg.setHostIp(address.getHostAddress());
                responseMsg.setHostPort(port);
                responseMsg.setNowtime(new Date().getTime());
                responseMsg.setDeviceCode(deviceCode);
                System.out.println(responseMsg);

//                Log.d("更新ui","55555");
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                killMyself();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        System.out.println("监听keycode:" + keyCode + "");
//        System.out.println("监听keycode:" + event + "");
        if (keyCode == KeyEvent.KEYCODE_BUTTON_SELECT) {
            unsigned_char_byte15_4 = 2;
            unsigned_char_byte15_0 = 66;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
            return true;
        }

//        if (keyCode == KeyEvent.KEYCODE_BUTTON_MODE) {
//            isphone = (boolean) SpUtils.get(MachineStatusActivity.this, AppContent.SaveInfoKey.ISPHONE, true);
//            if (isphone) {
//                isphone = false;
//                TvisPhone.setText("手柄模式");
//                SpUtils.put(MachineStatusActivity.this, AppContent.SaveInfoKey.ISPHONE, false);
//            } else {
//                isphone = true;
//                TvisPhone.setText("手机模式");
//                SpUtils.put(MachineStatusActivity.this, AppContent.SaveInfoKey.ISPHONE, true);
//
//            }
//            return true;
//        }
        if (keyCode == 100) {
            unsigned_char_byte15_4 = 0;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (keyCode == 97) {
            unsigned_char_byte15_4 = 3;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (keyCode == 102) {
            unsigned_char_byte15_4 = 7;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();

        } else if (keyCode == 103) {
            unsigned_char_byte15_4 = 8;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (keyCode == 108) {
            unsigned_char_byte15_4 = 2;
            unsigned_char_byte15_0 = 33;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        }


        if (keyCode == 99) {
            unsigned_char_byte15_4 = 1;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (keyCode == 96) {
            unsigned_char_byte15_4 = 2;
            unsigned_char_byte15_0 = 0;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        }
        if (keyCode == 4 || keyCode == 67) {
            return false;
        }

        return true;
    }


    float y;
    float x;
    float z;
    float rz;
    float hat_x;
    float hat_y;
    float lt;
    float rt;
    boolean isLeft = false;
    boolean isRight = false;
    boolean isLt = false;
    boolean isRt = false;

    @Override
    public boolean onGenericMotionEvent(MotionEvent event) {
//        //左摇杆
//        System.out.println(event.getAxisValue(MotionEvent.AXIS_X)+"::::====AXIS_X");
//        System.out.println(event.getAxisValue(MotionEvent.AXIS_Y)+"::::====AXIS_Y");
//        //右摇杆
//        System.out.println(event.getAxisValue(MotionEvent.AXIS_Z)+"::::====AXIS_Z");
//        System.out.println(event.getAxisValue(MotionEvent.AXIS_RZ)+"::::====AXIS_RZ");
//        //十字方向键
//        System.out.println("十字方向键");
//        System.out.println(event.getAxisValue(MotionEvent.AXIS_HAT_X)+"::::====AXIS_HAT_X");
//        System.out.println(event.getAxisValue(MotionEvent.AXIS_HAT_Y)+"::::====AXIS_HAT_Y");
        x = event.getAxisValue(MotionEvent.AXIS_X);
        y = event.getAxisValue(MotionEvent.AXIS_Y);
        z = event.getAxisValue(MotionEvent.AXIS_Z);
        rz = event.getAxisValue(MotionEvent.AXIS_RZ);
        hat_x = event.getAxisValue(MotionEvent.AXIS_HAT_X);
        hat_y = event.getAxisValue(MotionEvent.AXIS_HAT_Y);
        rt = event.getAxisValue(MotionEvent.AXIS_GAS);
        lt = event.getAxisValue(MotionEvent.AXIS_BRAKE);
        if (hat_x == -1.0) {
            unsigned_char_byte15_4 = 12;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (hat_x == 1.0) {
            unsigned_char_byte15_4 = 14;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (hat_y == -1.0) {
            unsigned_char_byte15_4 = 15;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (hat_y == 1.0) {
            unsigned_char_byte15_4 = 13;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        }

        if (lt > 0) {
            isLt = true;
            left = lt * 100;
            int s = (int) left;
            up = s;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        }
        if (isLt) {
            if (lt == 0) {
                isLt = false;
                up = 0;
                left = 0f;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
            }
        }

        if (rt > 0) {
            isRt = true;
            left = rt * 100;
            int s = (int) left;
            up = -s;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        }

        if (isRt) {
            if (rt == 0) {
                isRt = false;
                up = 0;
                left = 0f;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
            }
        }
        System.out.println(x + "^^^^" + y + "***" + z + "&&&" + rz);


        if (x - y > 0 && x + y < 0) {
            isLeft = true;
            up = y * 100;
            int s = (int) up;
            s = Math.abs(s);
            left = s;
            up = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();

        } else if (x - y < 0 && x + y > 0) {
            isLeft = true;
            up = y * 100;
            int s = (int) up;
            s = -s;
            left = s;
            up = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        }
        if (isLeft) {
            if (x == 0 && y == 0) {
                isLeft = false;
                left = 0;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
            }
        }


        if (z - rz < 0 && z + rz < 0) {
            isRight = true;
            zx_speed = -z;
            zx_speed = zx_speed * 100;
            int s = (int) zx_speed;
            zx_speed = s;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();

        } else if (z - rz > 0 && z + rz > 0) {
            isRight = true;
            zx_speed = z * 100;
            int s = (int) zx_speed;
//            s = Math.abs(s);
            zx_speed = -s;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();

        }
        if (isRight) {
            if (z == 0 && rz == 0) {
                isRight = false;
                zx_speed = 0;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
            }
        }

        return true;
    }

    private static String robotHost;
    private static int robotPort;

    private void sendUp(float up, float left, float zx, byte unsigned_0, byte unsigned_4) {
        robotHost = (String) SpUtils.get(MsgFeedbackActivity.this, AppContent.SaveInfoKey.DEVICEIP, "");
        robotPort = (int) SpUtils.get(MsgFeedbackActivity.this, AppContent.SaveInfoKey.DEVICEPORT, 1);
        RobotUdpUtil udp = new RobotUdpUtil();
        int test = 0;
        if (test == 0) {// 发起通信
            long[] unsigned_long_long = new long[]{0, 0};//时间，暂时都设为0;
            float[] float3 = new float[]{left, up, zx};// 顺序为x方向速度,y方向速度,转向速度
            float[] float2 = new float[]{0f, 0f};// 固定 0,0

            SendMsg sendMsg = new SendMsg(robotHost, robotPort, unsigned_long_long[0], unsigned_long_long[1])
                    .setFloat3(float3).setFloat2(float2)
                    .setUnsigned_char_byte15_0(unsigned_0)
                    .setUnsigned_char_byte15_4(unsigned_4)
                    .checkBuf();
            sendMsg(sendMsg);
        } else {
            // 接收通信
//            receiveMsg();
            udp.receiveMsg("00000001", 43795);
        }
    }



    private boolean sendMsg(SendMsg sendMsg) {
        boolean result = false;
        try {
            ds = new DatagramSocket();
            byte[] data = sendMsg.getbuf();
//            UDPSender.getInstance()
//                    .setInstructions(data)//设置发送的指令[可为空]
//                    .setReceiveTimeOut(70 * 1000)//设置接收超时时间[可不写，默认为60s]--超时70s就停止任务
//                    .setTargetPort(sendMsg.getServerPort())//设置发送的端口[必写]
////                    .setLocalReceivePort()//设置本机接收的端口[可不写，默认为目标端口]
//                    .setTargetIp(sendMsg.getServerHost())//设置目标ip地址，[可不写，默认广播]
//                    .schedule(2, 1000)//执行2次，间隔三秒执行（上一次结束到下一次开始的时间）
//                    .start(new UDPResultCallback() {
//
//                        @Override
//                        public void onStart() {
//                            //请求开始的时候回调
//                        }
//
//                        @Override
//                        public void onNext(UDPResult result) {
//                            //每收到一个结果的时候就回调
//                        }
//
//                        @Override
//                        public void onCompleted() {
//                            //请求结束的时候回调
//                        }
//
//                        @Override
//                        public void onError(Throwable throwable) {
//                            //当发生错误的时候回调
//                        }
//                    });


            DatagramPacket dp = new DatagramPacket(data, data.length,
                    InetAddress.getByName(sendMsg.getServerHost()),
                    sendMsg.getServerPort());
            ds.send(dp);
            result = true;
            System.out.println("发送：" + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ds != null) {
                ds.close();
            }
            return result;
        }
    }
}
